<template>
  <div class="dashboard-editor-container">
    <el-row :gutter="10" style="height: 100%">
      <el-col :span="12" style="height: 100%">
        <el-card class="box-card-top">
          <div slot="header" class="clearfix">
            <span class="fontWeight">芯片库分布情况</span>
          </div>
          <div class="chartContent">
            <el-radio-group v-model="chipType" class="groupBtn" @change="handleChange">
              <el-radio-button label="allChip">全部</el-radio-button>
              <el-radio-button label="mainChip">主控芯片</el-radio-button>
              <el-radio-button label="slaveChip">被控芯片</el-radio-button>
            </el-radio-group>
            <div v-show="chipType === 'allChip'" ref="allChipChart" class="chipChart" />
            <div v-show="chipType === 'mainChip'" ref="mainChipChart" class="chipChart" />
            <div v-show="chipType === 'slaveChip'" ref="slaveChipChart" class="chipChart" />
          </div>
        </el-card>
        <el-card class="box-card-bottom" style="margin-top: 10px">
          <div ref="projectCountChart" class="barChart" />
        </el-card>
      </el-col>
      <el-col :span="12" style="height: 100%">
        <el-card class="box-card-top">
          <div slot="header" class="clearfix">
            <span class="fontWeight">驱动库分布情况</span>
          </div>

          <div class="chartContent">
            <el-radio-group v-model="driverType" class="groupBtn" @change="handleChange">
              <el-radio-button label="allChipDriver">全部</el-radio-button>
              <el-radio-button label="mainChipDriver">主控芯片工程</el-radio-button>
              <el-radio-button label="slaveChipDriver">被控芯片驱动</el-radio-button>
            </el-radio-group>
            <div v-show="driverType === 'allChipDriver'" ref="allChipDriverChart" class="chipChart" />
            <div v-show="driverType === 'mainChipDriver'" ref="mainChipDriverChart" class="chipChart" />
            <div v-show="driverType === 'slaveChipDriver'" ref="slaveChipDriverChart" class="chipChart" />
          </div>
        </el-card>
        <el-card class="box-card-bottom" style="margin-top: 10px">
          <div class="chartContent">
            <el-select v-model="order" class="orderSelect" @change="getChipUseChartData">
              <el-option label="前五名" :value="5" />
              <el-option label="前十名" :value="10" />
              <el-option label="所有" value="" />
            </el-select>
            <div ref="chipUseChart" class="barChart" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  countChipDistribution,
  countDriverDistribution,
  countProjectDistribution,
  countChipUsage
} from '@/api/dashboard'
import * as echarts from 'echarts'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
export default {
  name: 'DashboardAdmin',
  components: {},
  data() {
    return {
      pieObj: {},
      // 芯片库分布情况
      chipType: 'allChip',
      allChipChart: null,
      mainChipChart: null,
      slaveChipChart: null,
      // 驱动库分布情况
      driverType: 'allChipDriver',
      allChipDriverChart: null,
      mainChipDriverChart: null,
      slaveChipDriverChart: null,

      projectCountChart: null,

      order: 5,
      chipUseChart: null,

      chipChartOption: {
        tooltip: {
          trigger: 'item',
          backgroundColor: '#ffffff',
          // formatter: '{a} <br/>{b} : {c} ({d}%)'
          formatter: '{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          icon: 'circle',
          right: 20,
          type: 'scroll',
          top: 'middle',
          data: []
        },
        graphic: [
          {
            // 一个图形元素，类型是 group，可以嵌套子节点。
            type: 'group',
            left: 'center', // 水平居中
            top: 'center', // 垂直居中
            children: [
              {
                type: 'text',
                top: 25,
                style: {
                  textAlign: 'center', // 设置文本水平居中
                  text: '总数', // 要显示的文本
                  fill: '#333', // 文本颜色
                  fontSize: 12 // 字体大小
                }
              },
              {
                type: 'text',
                top: 50,
                style: {
                  textAlign: 'center', // 设置文本水平居中
                  text: '50', // 要显示的文本
                  fill: '#000', // 文本颜色
                  fontSize: 20 // 字体大小
                }
              }
            ]
          }
        ],
        series: [
          {
            // name: '完成试验任务月占比',
            type: 'pie',
            radius: ['45%', '70%'],
            // center: ['40%', '50%'],
            avoidLabelOverlap: false, // 防止标签重叠
            // itemStyle: {
            //   borderRadius: 4
            // },
            label: {
              show: true,
              formatter: '{b} : {c} ({d}%)'
            },
            data: [],
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      },
      getallChipPieDataRequestId: generateUUID(),
      getmainChipPieDataRequestId: generateUUID(),
      getslaveChipPieDataRequestId: generateUUID(),
      getallChipDriverPieDataRequestId: generateUUID(),
      getmainChipDriverPieDataRequestId: generateUUID(),
      getslaveChipDriverDataRequestId: generateUUID(),
      countProjectDistributionRequestId: generateUUID(),
      countChipUsageRequestId: generateUUID()
    }
  },
  created() {
    window.addEventListener('resize', () => {
      this.allChipChart?.resize?.()
      this.mainChipChart?.resize?.()
      this.slaveChipChart?.resize?.()

      this.allChipDriverChart?.resize?.()
      this.mainChipDriverChart?.resize?.()
      this.slaveChipDriverChart?.resize?.()

      this.projectCountChart?.resize?.()
      this.chipUseChart?.resize?.()
    })
  },
  mounted() {
    this.getChipChartData('allChip', {})
    this.getChipChartData('mainChip', { chipType: 1 })
    this.getChipChartData('slaveChip', { chipType: 2 })
    this.getChipChartData('allChipDriver', {})
    this.getChipChartData('mainChipDriver', { driverType: 1 })
    this.getChipChartData('slaveChipDriver', { driverType: 2 })

    this.getProjectCountChartData()
    this.getChipUseChartData()

    receivedMessage(this.dataHandle)
  },
  beforeDestroy() {
    this.allChipChart?.dispose?.()
    this.mainChipChart?.dispose?.()
    this.slaveChipChart?.dispose?.()

    this.allChipDriverChart?.dispose?.()
    this.mainChipDriverChart?.dispose?.()
    this.slaveChipDriverChart?.dispose?.()

    this.projectCountChart?.dispose?.()
    this.chipUseChart?.dispose?.()
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      let res = e.data.response
      switch (e.data.webInfo.requestId) {
        case self.getallChipPieDataRequestId:
          self.initPieChart(res, self.pieObj[e.data.webInfo.requestId])
          break
        case self.getmainChipPieDataRequestId:
          self.initPieChart(res, self.pieObj[e.data.webInfo.requestId])
          break
        case self.getslaveChipPieDataRequestId:
          self.initPieChart(res, self.pieObj[e.data.webInfo.requestId])
          break
        case self.getallChipDriverPieDataRequestId:
          self.initPieChart(res, self.pieObj[e.data.webInfo.requestId])
          break
        case self.getmainChipDriverPieDataRequestId:
          self.initPieChart(res, self.pieObj[e.data.webInfo.requestId])
          break
        case self.getslaveChipDriverPieDataRequestId:
          self.initPieChart(res, self.pieObj[e.data.webInfo.requestId])
          break
        case self.countProjectDistributionRequestId:
          self.initProjectCountChart(res)
          break
        case self.countChipUsageRequestId:
          self.initChipUseChart(res)
          break
      }
    },
    handleChange(val) {
      this.$nextTick(() => {
        this[val + 'Chart'].resize()
      })
    },
    getChipChartData(name, params) {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this['get' + name + 'PieDataRequestId'] = generateUUID()
        this.pieObj[this['get' + name + 'PieDataRequestId']] = name
        let message = {
          RequestUrl:
            process.env.VUE_APP_URL +
            (['allChip', 'mainChip', 'slaveChip'].includes(name)
              ? '/homePage/countChipDistribution'
              : '/homePage/countDriverDistribution'),
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: params,
          WebInfo: {
            requestId: this['get' + name + 'PieDataRequestId']
          }
        }
        postMessage(message)
      } else {
        let operation = ['allChip', 'mainChip', 'slaveChip'].includes(name)
          ? countChipDistribution
          : countDriverDistribution
        operation(params).then((res) => {
          this.initPieChart(res, name)
        })
      }
    },
    initPieChart(res, name) {
      let chartData = res.data
      let chipChartOption = this.chipChartOption
      chipChartOption.legend.data = chartData.map((item) => item.name)
      chipChartOption.series[0].data = chartData
      chipChartOption.graphic[0].children[1].style.text = chartData.reduce(function (accumulator, currentValue) {
        return accumulator + currentValue.value
      }, 0)
      let chart = echarts.init(this.$refs[name + 'Chart'])
      chart.setOption(chipChartOption)
      this[name + 'Chart'] = chart
    },
    getProjectCountChartData() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.countProjectDistributionRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/homePage/countProjectDistribution',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: {},
          WebInfo: {
            requestId: this.countProjectDistributionRequestId
          }
        }
        postMessage(message)
      } else {
        countProjectDistribution().then((res) => {
          this.initProjectCountChart(res)
        })
      }
    },
    initProjectCountChart(res) {
      let option = {
        title: {
          text: '项目数量统计',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b0}: {c0}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: res.data.createTime,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            // name: 'Direct',
            type: 'bar',
            barWidth: '60%',
            data: res.data.projectCount,
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }
      this.projectCountChart = echarts.init(this.$refs.projectCountChart)
      this.projectCountChart.setOption(option)
    },
    getChipUseChartData(val) {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.countChipUsageRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/homePage/countChipUsage',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: { top: val ?? 5 },
          WebInfo: {
            requestId: this.countChipUsageRequestId
          }
        }
        postMessage(message)
      } else {
        countChipUsage({ top: val ?? 5 }).then((res) => {
          this.initChipUseChart(res)
        })
      }
    },
    initChipUseChart(res) {
      let option = {
        title: {
          text: '芯片使用情况分析',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b0}: {c0}'
        },
        dataZoom: {
          type: 'inside',
          startValue: 90,
          endValue: 100,
          orient: 'vertical',
          zoomOnMouseWheel: false,
          moveOnMouseWheel: true
        },
        grid: {
          left: 120,
          right: '4%',
          bottom: 30,
          containLabel: false
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01],
          min: 0,
          max: Math.max(...res.data.projectCount)
        },
        yAxis: {
          type: 'category',
          data: res.data.model.reverse(),
          axisLabel: {
            width: 110,
            overflow: 'truncate',
            ellipsis: '...'
          }
        },
        series: [
          {
            name: '',
            type: 'bar',
            label: {
              show: true,
              position: 'insideLeft'
            },
            data: res.data.projectCount.reverse()
          }
        ]
      }
      this.chipUseChart = this.chipUseChart ?? echarts.init(this.$refs.chipUseChart)
      this.chipUseChart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  height: 100%;
  padding: 20px;
  position: relative;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .fontWeight {
    font-weight: bold;
  }
  .box-card-top {
    height: calc(50% - 5px);
    /deep/.el-card__body {
      height: calc(100% - 56px);
    }
  }
  .box-card-bottom {
    height: calc(50% - 5px);
    /deep/.el-card__body {
      height: 100%;
    }
  }
  .chipChart {
    height: 100%;
    width: 100%;
  }
  .barChart {
    height: 100%;
    min-width: 600px;
    width: 100%;
  }
  .chartContent {
    height: 100%;
    width: 100%;
    position: relative;
    .groupBtn {
      position: absolute;
      z-index: 10;
    }
    .orderSelect {
      position: absolute;
      right: 20px;
      z-index: 10;
      width: 120px;
    }
  }
}
</style>
